#ifndef _THREAD_H_
#define _THREAD_H_

#include <iostream>
#include <string>
#include <pthread.h>
#include <cstring>
#include <cstdio>
#include <functional>
namespace ThreadModule
{
     static uint32_t number = 0;
     template<typename T>
    class Thread
    {
     using func_t  = std::function<void(T)>;

        public:
        Thread(func_t func,T data):
        _tid(0),
        _isdetach(false),
        _isrunning(false),
        res(nullptr),
        _func(func)
        _data(_data)
        {
            _name = "thread-"+ std::to_string(number++);
        }

        void enabledetach()
        {
            _isdetach=true;
        }
        void detach()//支持启动前后都可以分离
        {
            if(_isdetach)
            return ;
            if(_isrunning)
            pthread_detach(_tid);
            enabledetach();
        }
        void enablerunning()
        {
            _isrunning=true;
        }
        static void *myroutine(void* args)
        {
            Thread *self = static_cast<Thread*>(args);
            self->enablerunning();
            if(self->_isdetach)
            {
                self->detach();
            }
            self->_func(self->_data);
            return nullptr;
        }
        bool start()//线程启动
        {
            if(_isrunning)
            return false;
            int n = pthread_create(&_tid,nullptr,myroutine,nullptr);
            if(n>0)//成功返回零
            {
                std::cerr<<"create thread error: "<<strerror(n)<<std::endl;
                return false;
            }
            else
            {
                std::cout<<"success!!!"<<std::endl;
                 if(_isdetach)
            {
                detach();
            }
            enablerunning();
            return true;
            }
           
        }
        bool stop()
        {
            if(_isrunning)
            {
                int n = pthread_cancel(_tid);
                    if(n!=0)
                    {
                         std::cerr<<"cancel thread error: "<<strerror(n)<<std::endl;
                        return false;
                    }
                     else
                {
                std::cout<<_name<<"success!!!"<<std::endl;
                _isrunning=false;
                return true;
                 }
            }
            return true;
        }
        void join()
        {
            if(_isdetach)
            return ;
            int n = pthread_join(_tid,&res);
            if(n!=0)
            {
            std::cerr<<"cancel thread error: "<<strerror(n)<<std::endl;
            }
             else
            {
                std::cout<<"success!!!"<<std::endl;
            }
        }
        ~Thread()
        {}
        private:
        pthread_t _tid;
        std::string _name;
        bool _isdetach;
        bool _isrunning;
        void* res;
        func_t _func;
        T _data;
    };
}
#endif